package com.me.study.javaCore.dynamicProxy;

/**
 * 性能监视的实现类：相当于 AOP的 Advice
 *
 * @author ME
 * @date   2019/3/21 16:05
 */
public class PerformanceMonitor {

    /**
     * 通过 ThreadLocal 保存与调用线程相关的性能监视信息
      */
    private static ThreadLocal<MethodPerformance> performanceRecord = new ThreadLocal<MethodPerformance>();

    /**
     * 记录方法启动时间
     * @param method
     */
    public static void begin(String method) {
        System.out.println("[begin monitor]");
        MethodPerformance mp = new MethodPerformance(method);
        performanceRecord.set(mp);
    }

    public static void end() {
        System.out.print("[end monitor]\t");
        MethodPerformance mp = performanceRecord.get();
        // 打印方法耗时
        mp.printPerformance();
    }

    /**
     * 记录性能监视信息的类
     */
    private static class MethodPerformance {
        private long begin;
        private long end;
        private String methodName;

        public MethodPerformance(String methodName) {
            this.methodName = methodName;
            this.begin = System.currentTimeMillis();
        }

        public void printPerformance() {
            end = System.currentTimeMillis();
            System.out.printf("%s 花费[%d]毫秒。\n", methodName, end - begin);
        }
    }



}
